import sys


def login():
    username = input('输入用户名:')
    password = input('输入密码:')
    # 打开文件查看
    with open('Users.txt', 'r', encoding='utf-8') as rstream:
        # 逐行读取内容
        while True:
            # 读取一行内容
            user = rstream.readline()  # admin 123456\n
            # 判断有没有读取到内容
            if not user:
                print('用户名或者密码输入有误！')
                return False
            # 构造比较格式
            input_user = '{} {}\n'.format(username, password)
            # 如果用户输入的跟文件中的内容一致则认为用户登录成功
            if user == input_user:
                print('用户登录成功！')
                return username


def login_required(func):
    def wrapper(*args, **kwargs):
        if kwargs['userlogin'] == False:
            print('您需要先登录')
        else:
            f = func(*args, **kwargs)
            return f

    return wrapper


def show_books():
    print('---------图书馆里面的图书有:----------')
    with open('Books.txt', 'r', encoding='utf-8') as rstream:
        books = rstream.readlines()
        for book in books:
            print(book, end='')
        print('')


def register():
    username = input('用户名:')
    pwd = input('密码:')
    rpwd = input('确认密码:')
    username_exis = 0
    with open('Users.txt', 'r', encoding='utf-8') as f:
        while 1:
            existuser = f.readline()
            if username in existuser:
                print('用户名已存在!')
                return 0
            if not existuser:
                break
    if rpwd == pwd:
        with open('Users.txt', 'a', encoding='utf-8') as f:
            f.write('{} {}\n'.format(username, pwd))
        print('用户注册成功!')
    else:
        print('密码不一致！')


@login_required
def rend_books(username, userlogin):
    to_rend = '《' + input('要借的书名') + '》'
    tm = False  # 判断是否重名
    not_exist = True  # 判断借书的人在userbook.txt是否存在
    user_line = 0  # 用户所在的行
    book_i = 0  # 借的书所在的行
    book_find = False  # 判断书籍是否找到
    booksbuffer = []  # 将books信息缓存到列表中
    # 1、 判断在books列表中存在
    with open('Books.txt', 'r', encoding='utf-8') as f:
        books = f.readlines()
        for i, book in enumerate(books):
            if to_rend in book:
                print('查找到该书！')
                book_i = i
                book_find = True
                break
        if book_find == False:
            print('不存在这本书!')
            return False
        booksbuffer = books
    # 2、判断要借的书大于0
    if int(booksbuffer[book_i].split(' ')[1]) > 0:
        # 3、借书
        with open('User_book.txt', 'r', encoding='utf-8') as f:
            lines = f.readlines()
            # 判断用户是否存在和确定位置，并检验是否同名
            for i, line in enumerate(lines):
                if username in line:
                    not_exist = False
                    user_line = i
                    if to_rend in line:
                        tm = True
                        print('不可以借阅同名书籍')
            # 用户存在userbook,借书
            if not_exist == False:
                lines[user_line] = lines[user_line].rsplit('\n')[0] + ',' + to_rend + '\n'
                # 没有同名，保存信息
                if tm == False:
                    with open('User_book.txt', 'w', encoding='utf-8') as f:
                        for i in lines:
                            f.write(i)
                    print('借书成功')
            # 用户不存在userbook，借书
            else:
                msg = username + ' ' + to_rend + '\n'
                # 保存
                with open('User_book.txt', 'a', encoding='utf-8') as f:
                    f.write(msg)
                    print('借书成功')
        if tm == False:  # 没有同名，修改图书信息并保存
            # 数据-1
            booksbuffer[book_i] = booksbuffer[book_i].split(' ')[0] + ' ' + str(
                int(booksbuffer[book_i].split(' ')[1]) - 1) + '\n'
            # 保存修改内容
            with open('Books.txt', 'w', encoding='utf-8') as f:
                for i in booksbuffer:
                    f.write(i)
    else:
        print('该书已借完')


@login_required
def return_books(username, userlogin):
    to_return = '《' + input('要还的书名') + '》'
    book_i = 0  # 还书在books.txt哪行
    book_find = False  # 还书是否存在books.txt
    userbuffer = []  # 还书缓存 userbook.txt
    with open('User_book.txt', 'r', encoding='utf-8') as f:
        users = f.readlines()
        for i, user in enumerate(users):
            if username in user:
                # 还书
                tmp = user.split(' ')[1].split(',')
                if (len(tmp) == 0):
                    print("用户拥有书籍为空,不能还书哦！")
                    return
                tmp[-1] = tmp[-1].rstrip('\n')  # 清除\n换位符，准确比较
                if (to_return not in tmp):
                    print("要还的书不在用户拥有书籍中")
                    return
                msg = username + ' '
                tmp_list = []
                for i in tmp:  # 用户拥有的书籍遍历
                    if i != to_return:
                        tmp_list.append(i)
                msg = msg + ','.join(tmp_list) + "\n"  # 添加\n换位符
                userbuffer.append(msg)
                continue
            userbuffer.append(user)
    # 保存
    with open('User_book.txt', 'w', encoding='utf-8') as f:
        for i in userbuffer:
            f.write(i)
    # number+1
    with open('Books.txt', 'r', encoding='utf-8') as f:
        books = f.readlines()
        for i, book in enumerate(books):
            if to_return in book:
                book_i = i
                book_find = True
        if book_find:
            # 加1
            books[book_i] = books[book_i].split(' ')[0] + ' ' + str(int(books[book_i].split(' ')[1]) + 1) + '\n'
            # 保存修改内容
            with open('Books.txt', 'w', encoding='utf-8') as f:
                for i in books:
                    f.write(i)
                print('还书成功！')
        else:
            print('该书在书架中不存在！')


@login_required
def mod_pwd(username, userlogin):
    pwd_i = 0  # 密码在哪一行
    pwd_check = False  # 密码是否允许修改
    password = input('输入原密码:')
    # 打开文件查看
    with open('Users.txt', 'r', encoding='utf-8') as f:
        # 逐行读取内容
        pwds = f.readlines()
        for i, pwd in enumerate(pwds):
            if password in pwd:
                new_pwd = input('输入新密码:')
                pwd_i = i
                pwd_check = True
                break
            else:
                print('请输入正确的密码')
        if pwd_check:
            # 更新密码
            pwds[pwd_i] = username + ' ' + new_pwd + '\n'
            # 保存
            with open('Users.txt', 'w', encoding='utf-8') as f:
                for i in pwds:
                    f.write(i)
            print('修改密码成功')


@login_required
def logout(userlogin):
    print('已退出登录')
    return False;


if __name__ == '__main__':
    userlogin = False
    username = ""
    loopflag = True
    # 管理系统
    while loopflag:
        try:
            if (userlogin):
                LR = int(input('-----1.登录  2.注册 3.看书 4.借书 5.还书 6.修改密码 7.退出登录 | 用户名(' + username + ') -------'))
            else:
                LR = int(input('-----1.登录  2.注册 3.看书 4.借书 5.还书 6.修改密码 7.退出登录 -------'))
            if LR == 1:
                username = login()
                if username != False:
                    userlogin = True
                    print('登录:', username)
                else:
                    print("登录失败")
                    loopflag =False;
                    break;
            elif LR == 2:
                register()
            elif LR == 3:
                show_books()
            elif LR == 4:
                rend_books(username, userlogin=userlogin)
            elif LR == 5:
                return_books(username, userlogin=userlogin)
            elif LR == 6:
                mod_pwd(username, userlogin=userlogin)
            elif LR == 7:
                loopflag = logout(userlogin=userlogin)
                userlogin = False
                username = ""
            elif LR == -1:
                break
            else:
                print('请检查输入')
        except:
            print('请输入数字！')
